# -*- coding: utf8  -*-

import sys
import os

import gtk
import gtk.glade

from backup_system import backup_system
from xml.dom import minidom

class SaveDialog:

    def init_services_list(self):
        servicespath = os.path.dirname(__file__) + os.sep + 'xml/services.xml'
        xmldoc = minidom.parse(servicespath)
        services = xmldoc.getElementsByTagName('service')

        store = gtk.ListStore(str)

        for service in services:
            store.append([service.attributes["name"].value])
            self.services_list[service.attributes["name"].value] = service.attributes["smtp"].value

        self.comboServices.set_model(store)
        cell = gtk.CellRendererText()
        self.comboServices.pack_start(cell, True)
        self.comboServices.add_attribute(cell, 'text', 0)
        self.comboServices.set_active(0)

    def __init__(self, parent):
        builder = gtk.Builder()
        path = os.path.dirname(__file__) + os.sep + 'glade/saveDialog.glade'
        builder.add_from_file(path)

        self.save_dialog = builder.get_object("saveDialog")
        self.save_dialog.set_transient_for(parent)

        self.btnChoosePackages = builder.get_object("btnChoosePackages")
        self.btnChooseSources = builder.get_object("btnChooseSources")
        self.txtPackagesFile = builder.get_object("txtPackagesFile")
        self.txtSourcesFile = builder.get_object("txtSourcesFile")
        self.checkEmail = builder.get_object("checkEmail")
        self.txtEmail = builder.get_object("txtEmail")
        self.txtPassword = builder.get_object("txtPassword")
        self.comboServices = builder.get_object("comboServices")
        self.dlg_not_packages = builder.get_object("dlg_not_packages")
        self.dlg_not_sources = builder.get_object("dlg_not_sources")
        self.dlg_email_error = builder.get_object("dlg_email_error")

        self.services_list = {}

        self.init_services_list()

        builder.connect_signals(self)

    def on_checkEmail_toggled(self, widget):
        if(self.checkEmail.get_active()):
            self.txtEmail.set_editable(True)
            self.txtPassword.set_editable(True)
        else:
            self.txtEmail.set_text('')
            self.txtEmail.set_editable(False)
            self.txtPassword.set_text('')
            self.txtPassword.set_editable(False)

    def on_btnChoosePackages_clicked(self, widget):
        dialog_action =  gtk.FILE_CHOOSER_ACTION_SAVE
        dialog_buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)

        save_dialog = gtk.FileChooserDialog(title = 'Packages file', parent = None, action = dialog_action, buttons = dialog_buttons, backend = None)
        save_dialog.set_current_name('packages.txt')
        if save_dialog.run() == gtk.RESPONSE_OK:
            self.txtPackagesFile.set_text(save_dialog.get_filename())
            save_dialog.destroy()


    def on_btnChooseSources_clicked(self, widget):
        dialog_action =  gtk.FILE_CHOOSER_ACTION_SAVE
        dialog_buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)

        save_dialog = gtk.FileChooserDialog(title = 'Sources file', parent = None, action = dialog_action, buttons = dialog_buttons, backend = None)
        save_dialog.set_current_name('sources.list')
        if save_dialog.run() == gtk.RESPONSE_OK:
            self.txtSourcesFile.set_text(save_dialog.get_filename())
            save_dialog.destroy()

    def on_btnAceptar_clicked(self, widget):
        if self.txtPackagesFile.get_text() == '':
            self.dlg_not_packages.run()
            self.dlg_not_packages.hide()
        elif self.txtSourcesFile.get_text() == '':
            self.dlg_not_sources.run()
            self.dlg_not_sources.hide()
        else:
            backup_system.save_packages(self.txtPackagesFile.get_text())
            backup_system.save_sources(self.txtSourcesFile.get_text())
            if self.checkEmail.get_active():
                try:
                    attach_list = [self.txtPackagesFile.get_text(), self.txtSourcesFile.get_text()]
                    backup_system.email_backup(self.txtEmail.get_text(), self.txtPassword.get_text(), attach_list, self.services_list[self.comboServices.get_active_text()])
                except Exception:
                    self.dlg_email_error.run()
                    self.dlg_email_error.hide()

            self.save_dialog.destroy()

    def on_btnCancelar_clicked(self, widget):
        self.save_dialog.destroy()

